from django.db.models import Q
from django.shortcuts import render
from rbac.models import WorkFlowModel,Role
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import PowerWorkFlowModel,EAWorkFlowModel,PositionModel,TaskWorkFlowModel,RecordWorkFlowModel
from rbac.models import WorkFlowModel,UserModel
from tools.wfagent import wfagent
import json
from tools.sendemail import send_email_view


# Create your views here.

class AddWorkFlowView(APIView):
    def post(self,request):
        name = request.data.get('name')
        params = request.data.get('params')
        WorkFlowModel.objects.create(name=name,params=params,status=2)
        return Response('添加成功')


    def get(self,request):
        workflows = WorkFlowModel.objects.values('id',"name")
        return Response(workflows)



class PWFView(APIView):
    def get(self,request):
        id = request.query_params.get("id")
        role = Role.objects.values('id','name')
        all_data = [{'key':i['id'],'label':i['name']} for i in role]
        data = PowerWorkFlowModel.objects.filter(workflow_id=id).values('role__id')
        data = list([i['role__id'] for i in data])
        return Response({"all":all_data,'has':data})

    def post(self,request):
        id = request.data.get('id')
        print(id)
        roles = request.data.get('roles')
        print(roles)
        wf = WorkFlowModel.objects.get(id=id)
        if wf.pwf_workflow.all().exists():
            pwf = wf.pwf_workflow.first()
            pwf.role.set(roles)
            return Response('更新成功')

        pwf = PowerWorkFlowModel.objects.create(workflow=wf)
        pwf.role.set(roles)
        return Response('添加成功')


class EAWorkFlowView(APIView):
    def get(self,request):
        id = request.query_params.get("id")
        print(id)
        data = EAWorkFlowModel.objects.filter(workflow_id=id).all()
        if not data:
            return Response('400')
        data = [{'level':i.level,'position':i.position.id} for i in data]

        return Response(data)



class PositionView(APIView):
    def get(self,request):
        positions = PositionModel.objects.values('id', 'name')
        return Response(positions)

    def post(self,request):
        id = request.data.get('id')

        data = request.data.get('data')
        ea = EAWorkFlowModel.objects.filter(workflow_id=id).all()
        if ea.exists():
            ea.delete()
        for item in data:
            EAWorkFlowModel.objects.create(workflow_id=id,position_id=item['position'],level=item['level'])
        return Response('添加成功')


# 获得角色的工作流
class GetAllWorkFlowView(APIView):
    def get(self,request):
        role_id = request.query_params.get('role_id')
        role = [Role.objects.get(id=role_id),]
        data = PowerWorkFlowModel.objects.filter(Q(role__in=role) & Q(workflow__status=1)).values('workflow__id','workflow__name')
        return Response(data)



class GetDetailWorkFlowView(APIView):
    def get(self,request):
        user_id = request.query_params.get('user_id')
        user_department = UserModel.objects.get(id=user_id).department_id
        id = request.query_params.get('id')
        data = WorkFlowModel.objects.filter(id=id).values('id','name','params')
        ea_data = EAWorkFlowModel.objects.filter(workflow_id=id).values('level','position_id').order_by('level')
        ea_data_list= []
        p1_data = UserModel.objects.filter(Q(position_id=ea_data[0]['position_id']) & Q(department_id=user_department)).values('id','username','position__name','role__name','position_id').first()
        ea_data_list.append(p1_data)
        pos_list = [int(i['position_id']) for i in ea_data[1:]]
        p2_data = UserModel.objects.filter(position_id__in=pos_list).values('id','username','position__name','role__name','position_id')
        for i in p2_data:
            ea_data_list.append(i)


        ea_data_dict = {i['position_id']:i for i in list(ea_data_list)}
        data_list = []
        for i in ea_data:
            ea_data_dict[i['position_id']]['level'] = i['level']
            data_list.append(ea_data_dict[i['position_id']])





        return Response({'data':data,'ea_data':data_list})


class GetTaskView(APIView):
    def post(self,request):
        user_id = request.data.get('user_id')
        params = json.loads(request.data.get('params'))
        wf_id = request.data.get('workflow_id')
        ea_user_id = request.data.get('ea_user_id')
        data = json.dumps({'user_id':user_id,'params':params,'workflow_id':wf_id,'ea_user_id':ea_user_id})
        wfagent(data)
        return Response('添加成功')













